//
//  UIDevFormTableViewCell.swift
//  DevFormView
//
//  Created by dev on 15/9/16.
//  Copyright (c) 2015年 devilved. All rights reserved.
//

import UIKit

class UIDevFormTableViewCell: UITableViewCell {
    
    var field:DevFormField?

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}

class DevFormSection:NSObject,UIGestureRecognizerDelegate {
    
    var labels:[[String:AnyObject]]?
    
    var fields:[DevFormField] = []
    
    var height:CGFloat = 12
    
    var controlHeight:CGFloat = 32
    
    var backgroundColor:UIColor?
    
    var view:UIView?
    
    var formTableView:UIDevFormTableView!
    
    var onClick:(UIDevFormTableView!, DevFormSection!, UIButton!) -> Void = {(formTableView:UIDevFormTableView!,section:DevFormSection!, sender:UIButton!) -> Void in}
    
    func getDevFormSectionView(formTableView:UIDevFormTableView) -> UIView? {
        self.formTableView = formTableView
        if self.view == nil {
            self.initDevFormSectionView(formTableView)
        }
        return view
    }
    
    func initDevFormSectionView(formTableView:UIDevFormTableView) {
        self.view = UIView()
        let view:UIView = self.view!
        if let backgroundColor:UIColor = self.backgroundColor {
            view.backgroundColor = backgroundColor
        } else {
            view.backgroundColor = UIColor.groupTableViewBackgroundColor()
        }
        if let labels = self.labels {
            var x = formTableView.separatorInset.left
            let y = (self.height - self.controlHeight) / 2
            for var i=0; i<labels.count; i++ {
                let label:[String:AnyObject] = labels[i]
                if let text = label["text"] as? String {
                    let button:UIButton = UIButton()
                    button.tag = i
                    button.setTitle(text, forState: UIControlState.Normal)
                    if let color = label["color"] as? UIColor {
                        button.setTitleColor(color, forState: UIControlState.Normal)
                    } else {
                        button.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
                    }
                    if let font = label["font"] as? UIFont {
                        button.titleLabel?.font = font
                    }
                    let width = text.sizeWithAttributes([NSFontAttributeName: button.titleLabel!.font!]).width
                    button.frame = CGRectMake(x, y, width, controlHeight)
                    button.addTarget(self, action: "onButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
                    view.addSubview(button)
                    x = x + width
                }
            }
        }
        let gestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer()
        gestureRecognizer.delegate = self
        gestureRecognizer.addTarget(self, action: "onSectionTouch")
        view.addGestureRecognizer(gestureRecognizer)
    }
    
    func onSectionTouch() {
        self.formTableView.endEditing(true)
    }
    
    func onButtonClick(sender:UIButton!) {
        self.formTableView.endEditing(true)
        self.onClick(self.formTableView, self, sender)
    }
    
}

class DevFormField:NSObject {
    
    var name:String!
    
    var label:String!
    
    var defaultValue:AnyObject? {
        get {
            return self.value
        }
        set {
            self.value = newValue
        }
    }
    
    var view:UIView?
    
    var labelFont:UIFont?
    
    var height:CGFloat = 40
    
    var controlHeight:CGFloat = 32
    
    var backgroundColor:UIColor?
    
    var formTableViewCell:UIDevFormTableViewCell?
    
    var formTableView:UIDevFormTableView!
    
    var delegate:DevFormFieldDelegate?
    
    var value:AnyObject?
    
    var onInitTableViewCell:(UIDevFormTableView!, DevFormField!, UIDevFormTableViewCell!) ->Void = {(formTableView:UIDevFormTableView!, formField:DevFormField!, cell:UIDevFormTableViewCell!)->Void in }
    
    var onInitDevFormFieldView:(UIDevFormTableView!, DevFormField!)->Void = {(formTableView:UIDevFormTableView!, formField:DevFormField!)->Void in }
    
    init(name:String!, label:String!) {
        self.name = name
        self.label = label
    }
    
    func addToFormTableViewCell(formTableView:UIDevFormTableView, cell:UIDevFormTableViewCell) {
        if let field:DevFormField = cell.field {
            if let view:UIView = field.view {
                if field.formTableViewCell == cell {
                    view.removeFromSuperview()
                    field.formTableViewCell = nil
                }
                cell.removeConstraints(cell.constraints)
                cell.field = nil
            }
        }
        self.formTableView = formTableView
        self.formTableViewCell = cell
        cell.field = self
        var needInitConstraints:Bool = false
        if self.view == nil {
            needInitConstraints = true
            self.initDevFormFieldView()
            self.onInitDevFormFieldView(formTableView, self)
        }
        cell.addSubview(self.view!)
        if needInitConstraints {
            self.initConstraints()
        }
        //设置约束
        let views = ["cellView": self.view!]
        self.view!.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[cellView]|", options: NSLayoutFormatOptions(), metrics: nil, views: views))
        
        self.view!.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[cellView]|", options: NSLayoutFormatOptions(), metrics: nil, views: views))
    }
    
    var textLabel:UILabel?
    
    var textLabelWidth:NSLayoutConstraint?
    
    var textLabelHeight:NSLayoutConstraint?
    
    func initDevFormFieldView() {
        let left:CGFloat = self.formTableView.separatorInset.left > 0 ? self.formTableView.separatorInset.left : 15
        
        self.view = UIView()
        let main:UIView = self.view!
        main.frame = CGRectMake(0, 0, self.formTableView.frame.width, height)
        if let value:AnyObject = self.defaultValue {
            self.value = value
        }
        if let backgroundColor:UIColor = self.backgroundColor {
            main.backgroundColor = backgroundColor
        }
        
        self.textLabel = UILabel()
        let label = self.textLabel!
        if let font:UIFont = self.labelFont {
            label.font = font
        }
        let size:CGSize = DevStringUtils.sizeOfString(self.label, font: self.textLabel!.font)
        
        label.frame = CGRectMake(left, (self.height - size.height) / 2, size.width, size.height)
        
        label.text = self.label
        
        main.addSubview(label)

    }
    
    func initConstraints() {
        let main:UIView = self.view!
        let size:CGSize = DevStringUtils.sizeOfString(self.label, font: self.textLabel!.font)
        let left:CGFloat = self.formTableView.separatorInset.left > 0 ? self.formTableView.separatorInset.left : 15
        let label = self.textLabel!
        label.translatesAutoresizingMaskIntoConstraints = false
        
        main.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: main, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: left))
        
        main.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: main, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        self.textLabelWidth = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: size.width + 5)
        main.addConstraint(self.textLabelWidth!)
        
        self.textLabelHeight = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: size.height)
        main.addConstraint(self.textLabelHeight!)
    }
    
    func isAnimated() -> Bool {
        return true
    }
    
    func click() {
        self.formTableView.endEditing(true)
        self.focus()
    }
    
    func focus() {
        if let cell = self.formTableViewCell {
            self.formTableView.setCurrentSelectedCell(cell)
        }
        if let delegate:DevFormFieldDelegate = self.delegate {
            delegate.formField(onFocus: self, formTableView: self.formTableView)
        }
    }
    
    func setFieldValue(value:AnyObject?) {
        if let newValue:AnyObject = value {
            if !newValue.isEqual(self.value) {
                if let delegate:DevFormFieldDelegate = self.delegate {
                    delegate.formField(onValueChange: self, formTableView:self.formTableView, newValue:newValue, oldValue:self.value)
                }
            }
            self.value = newValue
        }
    }
    
    func getFieldValue() -> AnyObject? {
        if let value:AnyObject = self.value {
            return value
        }
        return nil
    }
    
    func getEditableView() -> UIView? {
        return nil
    }
    
}

protocol DevFormFieldDelegate:NSObjectProtocol {
    
    func formField(onValueChange formField:DevFormField, formTableView:UIDevFormTableView!, newValue:AnyObject!, oldValue:AnyObject?) -> Void
    
    func formField(onFocus formField:DevFormField, formTableView:UIDevFormTableView!) -> Void
    
}